<?php
/**
 * 商品类
 */


class Goods extends MyBase{
	public $goodslist = null;
	
	protected $tb_goods;
	protected $tb_goods_trends;
	protected $tb_goods_album;
	protected $tb_goods_attr;
	protected $tb_goods_spec;
	
	
	function __construct() {
		parent::__construct('goods.id');
		
		$this->tb_goods = $this->get_tbname('goods');
		$this->tb_goods_trends = $this->get_tbname('goods_trends');
		$this->tb_goods_album = $this->get_tbname('goods_album');
		$this->tb_goods_attr = $this->get_tbname('goods_attr');
		$this->tb_goods_spec = $this->get_tbname('goods_spec');
		
		$this->goodslist = array();
	}
	
	public function update($id, $data, $condition = ''){
		$select = array('id' => $id);
		if(!empty($condition)){
			$select['kept'] = $condition;
		}
		$data['updatetime'] = TIME;
		if(!isset($this->goodslist[$id]))$this->goodslist[$id] = array();
		array_update($this->goodslist[$id], $data);
		return $this->db->update($this->tb_goods, $select, $data);
	}
	
	/**
	 * 修改商品
	 */
	public function edit($post){
		$id = empty($post['id']) ? 0 : intval($post['id']);
		$sn = empty($post['sn']) ? get_uuid() : trim($post['sn']);
		
		$select = array('sn' => $post['sn']);
		if($id > 0)$select['kept'] = " AND id!={$id}";
		$rs = $this->db->get_row($this->tb_goods, $select, 'id');
		if(!empty($rs)){return lang('already').lang('exist');}
		
		$select = array('catid' => $post['catid'], 'name' => $post['name']);
		if($id > 0)$select['kept'] = " AND id!={$id}";
		$rs = $this->db->get_row($this->tb_goods, $select, 'id');
		if(!empty($rs)){return lang('already').lang('exist');}
		
		if($id > 0){
			$goods = $this->get_row($id, 'id,filename,addtime');
		}
		$post['show'] = empty($post['show']) ? 0 : intval($post['show']);
		$post['recommend'] = empty($post['recommend']) || $post['recommend'] == 'normal' ? '' : trim($post['recommend']);
		if(empty($post['summary']))$post['summary'] = String::summary(stripslashes($post['describe']), SUMMARY_LEN);
		if($post['label'] != '' && $post['labeltype'] == '0'){
			$post['labeltype'] = 3;	// 自定义
		}
		$data = array(
			'sn'			=> $sn,
			'catid'			=> $post['catid'],
			'name'			=> $post['name'],
			'brand'			=> $post['brand'],
			'rank'			=> $post['rank'],
			'show'			=> $post['show'] == 1 ? 1 : 0,
			'recommend'		=> $post['recommend'],
			'labeltype'		=> $post['labeltype'],
			'label'			=> $post['label'],
			'filename'		=> trim($post['filename']),
			'quantity'		=> $post['quantity'],
			'quantityunit'	=> $post['quantityunit'],
			'market_price'	=> $post['market_price'],
			'price'			=> $post['price'],
			'weight'		=> format_weight_in($post['weight'], $post['weightunit']),
			'weightunit'	=> $post['weightunit'],
			'summary'		=> $post['summary'], 
			'describe'		=> $post['describe'],
			'salesinfo'		=> $post['salesinfo'],
			'related_news'	=> $post['related_news'],
			'combine_goods'	=> $post['combine_goods'],
			'combine_price'	=> $post['combine_price'],
			'fittings'		=> empty($post['fittings']) ? '' : serialize($post['fittings']),
		);
		if($id > 0){
			$data['updatetime'] = empty($post['updatetime']) ? TIME : strtotime($post['updatetime']); 
			$r = $this->db->update($this->tb_goods, array('id' => $id), $data);
		}else{
			$data['addtime'] = empty($post['addtime']) ? TIME : strtotime($post['addtime']);
			$managerinfo = & VS::get('managerinfo');
			if(!empty($managerinfo)){$data['managerid'] = $managerinfo['userid'];}	// 记录商品隶属管理员
			$r = $id = $this->db->insert($this->tb_goods, $data);
			if($id > 0){
				$this->db->replace($this->tb_goods_trends, array('goodsid' => $id));
			}
		}
		if($r >= 0){
			// 删除可能存在的静态页面
			if(isset($goods)){
				$this->delete_html_file($id, $goods['addtime'], $goods['filename']);
			}
			// 图片处理
			$cover = $this->edit_img($id, $post);
			if(!empty($cover)){
				$this->db->update($this->tb_goods, array('id' => $id), array('cover' => $cover));
			}
			// 属性
			//if(!empty($post['attrs'])){
				$r = $this->edit_attr($id, $post['attrs']);
			//}
			// 规格，销售属性
			//if(!empty($post['specids'])){
				$r = $this->edit_spec($id, $post['specids'], $post['specs'], $post['quantitys']);
			//}
			// 人气组合
			$this->cover_combine_goods($id, $post['combine_goods']);
		}
		return $r;
	}
	
	public function edit_img($goodsid, $post){
		if(empty($post['album_alt'])){
			return '';
		}
		$oUpload = new Upload(array(
			'upload_form_field'	=> 'album_img',
			'auto_date_dir'		=> true,
			'out_file_dir'		=> UP_PTH.'goods/',
			'allowed_file_ext'	=> array('gif', 'jpg', 'jpeg', 'png'),
		));
		$img_arr = $oUpload->upload_process();
		if(!is_array($img_arr))$img_arr = array();
		
		$cover = '';
		foreach($post['album_alt'] as $key => $alt){
			$img_id		= 0;
			if(!empty($post['album_info'][$key])){
				list($img_id, $img_path) = explode('|', $post['album_info'][$key]);
			}
			$data =  array(
				'goodsid'	=> $goodsid,
				'alt'		=> $post['album_alt'][$key],
				'rank'		=> intval($post['album_rank'][$key]),
				'iscover'	=> 0,
			);
			if($alt == '#@del@#' || isset($img_arr[$key])){
				// 删除图片
				if($img_id > 0){
					@unlink(UP_PTH.$img_path);
					@unlink(UP_PTH.'thumb/400_225/'.$img_path);
					@unlink(UP_PTH.'thumb/200_120/'.$img_path);
				
					if($alt == '#@del@#'){
						$this->db->delete($this->tb_goods_album, array('id' => $img_id));
						continue;
					}
				}
				
				if(isset($img_arr[$key])){
					$img_path = $img_arr[$key];
					$data['path'] = str_replace(UP_PTH, '', $img_path);
					$this->make_thumb($img_path);
				
					if(
						(isset($post['album_cover']) && $post['album_cover'] == $key) || 
						$key == 1
					){	// 封面 
						$cover = $data['path'];
						$data['iscover'] = 1;
					}
				}
			}elseif(isset($post['album_cover']) && $post['album_cover'] == $key && !empty($img_path)){
				$cover = $img_path;
				$data['iscover'] = 1;
			}
			
			if($img_id > 0){
				$data['updatetime'] = TIME;
				$this->db->update($this->tb_goods_album, array('id' => $img_id), $data);
			}elseif(isset($data['path'])){
				$data['addtime'] = TIME;
				$this->db->insert($this->tb_goods_album, $data);
			}
		}
		return $cover;
	}
	
	public function make_thumb($img_path){
		File::resize($img_path, 400, 400, 'basic', true);
		File::resize($img_path, 200, 180, 'basic', true);
		File::resize($img_path, 160, 160, 'adaptive', true);
		// File::resize($img_path, 180, 135, 'adaptive', true);
		File::resize($img_path, 92, 70, 'basic', true);
	}
	
	public function edit_attr($id, $attrs){
		if(empty($attrs))$attrs = array();
		$attrs_old = $this->get_attrs($id);
		if(!empty($attrs_old)){
			foreach($attrs_old as $prototypeid => $value){
				if(is_array($value['value'])){
					foreach($value['value'] as $key => $item){
						if(isset($attrs[$prototypeid]) && is_array($attrs[$prototypeid]) && in_array($key, $attrs[$prototypeid])){
							continue;
						}
						$this->db->delete($this->tb_goods_attr, array('goodsid' => $id, 'prototypeid' => $prototypeid, 'value' => $key));
					}
				}else{
					if(isset($attrs[$prototypeid]) && $attrs[$prototypeid] == $value['value']){
						continue;
					}
					$this->db->delete($this->tb_goods_attr, array('goodsid' => $id, 'prototypeid' => $prototypeid, 'value' => $value['value']));
				}
			}
		}
		
		foreach($attrs as $prototypeid => $value){
			if(is_array($value)){
				foreach($value as $item){
					$select = array('goodsid' => $id, 'prototypeid' => $prototypeid, 'value' => $item);
					$row = $this->db->get_row($this->tb_goods_attr, $select);
					if(empty($row)){
						$data = array(
							'goodsid'		=> $id,
							'prototypeid'	=> $prototypeid,
							'value'			=> $item,
							'addtime'		=> TIME,
						);
						$this->db->replace($this->tb_goods_attr, $data);
					}else{
						$data = array(
							'updatetime'	=> TIME,
						);
						$this->db->update($this->tb_goods_attr, $select, $data);
					}
				}
			}else{
				$select = array('goodsid' => $id, 'prototypeid' => $prototypeid);
				$row = $this->db->get_row($this->tb_goods_attr, $select);
				if(empty($row)){
					$data = array(
						'goodsid'		=> $id,
						'prototypeid'	=> $prototypeid,
						'value'			=> $attrs[$prototypeid],
						'addtime'		=> TIME,
					);
					$this->db->insert($this->tb_goods_attr, $data);
				}else{
					$data = array(
						'value'			=> $attrs[$prototypeid],
						'updatetime'	=> TIME,
					);
					$this->db->update($this->tb_goods_attr, $select, $data);
				}
			}
		}
		
		return true;
	}
	
	// 编辑规格
	public function edit_spec($id, $specids, $specs, $quantitys){
		if(empty($specids))$specids = array();
		if(empty($specs))$specs = array();
		if(empty($quantitys))$quantitys = array();
		
		$specs_old = $this->get_specs($id, true);
		$specs_old = $specs_old['specs'];
		if(!empty($specs_old)){	// 删除旧的不用的规格
			foreach($specs_old as $prototypeid => $value){
				if(is_array($value['value'])){
					foreach($value['value'] as $key => $item){
						if(isset($specids[$prototypeid]) && in_array($key, $specids[$prototypeid])){
							continue;
						}
						$this->db->delete($this->tb_goods_spec, array('goodsid' => $id, 'prototypeid' => $prototypeid, 'value' => $key));
					}
				}else{
					if(isset($specids[$prototypeid]) && $specids[$prototypeid] == $value['value']){
						continue;
					}
					$this->db->delete($this->tb_goods_spec, array('goodsid' => $id, 'prototypeid' => $prototypeid));
				}
			}
		}
			
		foreach($specids as $prototypeid => $value){
			if(is_array($value)){
				foreach($value as $item){
					$quantity = trim($quantitys[$prototypeid][$item]);
					if($quantity === ''){
						$autofill = 1;
					}else{
						$autofill = 0;
					}
					$select = array('goodsid' => $id, 'prototypeid' => $prototypeid, 'value' => $item);
					$row = $this->db->get_row($this->tb_goods_spec, $select);
					if(empty($row)){
						$data = array(
							'goodsid'		=> $id,
							'prototypeid'	=> $prototypeid,
							'value'			=> $item,
							'price'			=> floatval($specs[$prototypeid][$item]),
							'quantity'		=> intval($quantity),
							'autofill'		=> $autofill,
							'addtime'		=> TIME,
						);
						$this->db->replace($this->tb_goods_spec, $data);
					}else{
						$data = array(
							'price'			=> floatval($specs[$prototypeid][$item]),
							'quantity'		=> intval($quantity),
							'autofill'		=> $autofill,
							'updatetime'	=> TIME,
						);
						$this->db->update($this->tb_goods_spec, $select, $data);
					}
				}
			}else{
				if(isset($quantitys[$prototypeid]) && isset($quantitys[$prototypeid]['quantity'])){
					$quantity = trim($quantitys[$prototypeid]['quantity']);
				}else{
					$quantity = '';
				}
				if($quantity === ''){
					$autofill = 1;
				}else{
					$autofill = 0;
				}
				$select = array('goodsid' => $id, 'prototypeid' => $prototypeid);
				$row = $this->db->get_row($this->tb_goods_spec, $select);
				if(empty($row)){
					$data = array(
						'goodsid'		=> $id,
						'prototypeid'	=> $prototypeid,
						'value'			=> $specs[$prototypeid]['value'],
						'price'			=> floatval($specs[$prototypeid]['price']),
						'quantity'		=> intval($quantity),
						'autofill'		=> $autofill,
						'addtime'		=> TIME,
					);
					$this->db->insert($this->tb_goods_spec, $data);
				}else{
					$price = isset($specs[$prototypeid]['price']) ? floatval($specs[$prototypeid]['price']) : 0;
					$data = array(
						'value'			=> $specs[$prototypeid]['value'],
						'price'			=> $price,
						'quantity'		=> intval($quantity),
						'autofill'		=> $autofill,
						'islack'		=> 0,
						'updatetime'	=> TIME,
					);
					$this->db->update($this->tb_goods_spec, $select, $data);
				}
			}
		}
		return true;
	}

	// 人气组合，如果组合的商品的相应字段为空，则更新
	public function cover_combine_goods($goodsid, $combine_goods){
		$ids = explode(',', trim($combine_goods, ', '));
		foreach($ids as $k => $id){
			if(empty($id))continue;
			$goods = $this->get_row($id, '`combine_goods`,`addtime`,`filename`');
			if(empty($goods['combine_goods'])){
				$combine_goods = $ids;
				unset($combine_goods[$k]);
				$combine_goods[] = $goodsid;
				$combine_goods = ','.(implode(',', $combine_goods)).',';
				// 更新组合商品的相应字段
				$this->update($id, array('combine_goods' => $combine_goods));
				// 删除可能存在的静态页面
				$this->delete_html_file($id, $goods['addtime'], $goods['filename']);
			}
		}
	}
	
	// 缺货登记
	public function lack($goodsid, $prototypeid, $value){
		return $this->db->update($this->tb_goods_spec, array('goodsid' => $goodsid, 'prototypeid' => $prototypeid, 'value' => $value), array(
			'islack' 	=> 1,
			'updatetime'=> TIME,
		));
	}

	/*******************************************************************************
	 * 更新动态信息
	 *******************************************************************************/

	public function update_trends($goodsid, $trends = array()){
		$rs = $this->get_trends($goodsid, '`goodsid`');
		if(empty($rs)){
			$trends['goodsid'] = $goodsid;
			return $this->db->replace($this->tb_goods_trends, $trends);
		}else{
			return $this->db->update($this->tb_goods_trends, array('goodsid' => $goodsid), $trends);
		}
	}
	public function inc_trends($goodsid, $field, $number = 1){
		$rs = $this->get_trends($goodsid, '*');
		if(empty($rs)){
			$trends = array(
				'goodsid'	=> $goodsid,
				$field		=> $number,
			);
			return $this->db->replace($this->tb_goods_trends, $trends);
		}else{
			if(!isset($rs[$field]))return false;
			$trends = array($field => $rs[$field] + $number);
			return $this->db->update($this->tb_goods_trends, array('goodsid' => $goodsid), $trends);
		}
	}
	public function dec_trends($goodsid, $field, $number = 1){
		$rs = $this->get_trends($goodsid, '*');
		if(empty($rs)){
			$trends = array(
				'goodsid'	=> $goodsid,
				$field		=> 0,
			);
			return $this->db->replace($this->tb_goods_trends, $trends);
		}else{
			if(!isset($rs[$field]))return false;
			$trends = array($field => $rs[$field] - $number);
			if($trends[$field] < 0)$trends[$field] = 0;
			return $this->db->update($this->tb_goods_trends, array('goodsid' => $goodsid), $trends);
		}
	}
	
	/*******************************************************************************
	 * 更新排序与显示开关
	 *******************************************************************************/
	public function rank($post){
		$ranks = empty($post['rank']) ? array() : $post['rank'];
		if(!is_array($ranks))return false;
		$shows = empty($post['show']) ? array() : $post['show'];
		$taobaoids = empty($post['taobaoid']) ? array() : $post['taobaoid'];
		$quantitys = empty($post['quantity']) ? array() : $post['quantity'];
		$recommends = empty($post['recommend']) ? array() : $post['recommend'];

		$iRtn = 0;
		$time = TIME;
		foreach($ranks as $id => $rank){
			$data = array(
				'rank'		 => $rank, 
				'updatetime' => $time,
			);
			if(isset($shows[$id])){
				$data['show'] = 1;
			}else{
				$data['show'] = 0;
			}
			if(isset($taobaoids[$id])){
				$data['taobaoid'] = $taobaoids[$id];
			}
			if(isset($quantitys[$id])){
				$data['quantity'] = $quantitys[$id];
			}
			if(isset($recommends[$id])){
				$data['recommend'] = $recommends[$id] == 'normal' ? '' : trim($recommends[$id]);
			}
			if($this->db->update($this->tb_goods, array('id' => $id), $data)){
				$iRtn ++;
			}
		}
		return $iRtn;
	}
	
	public function add_hits($id){
		return $this->db->query("UPDATE `{$this->tb_goods}` SET `hits`=`hits`+1 WHERE `id`={$id} LIMIT 1");
	}
			
	/**
	 * 删除商品，仅标识，不作物理删除
	 */
	public function del($post){
		if(!is_array($post['list']))$post['list'] = array($post['list']);
		$iRtn = 0;
		foreach($post['list'] as $id){
			$r = $this->db->update($this->tb_goods, array('id' => $id), array('isdel' => 1));
			/* $goods = $this->get_row($id, 'id,filename,addtime');
			if(empty($goods) || empty($goods['id']))continue;
			$r = $this->db->delete($this->tb_goods, array('id' => $id));
			$album_list = $this->get_album_all($id);
			if(!empty($album_list) && !empty($album_list['list'])){
				foreach($album_list['list'] as $album){
					// 删除图片
					@unlink(UP_PTH.$album['path'].'/'.$album['base'].'.'.$album['ext']);
					@unlink(UP_PTH.'thumb/400_225/'.$album['path']);
					@unlink(UP_PTH.'thumb/200_120/'.$album['path']);
				}
				$this->db->delete($this->tb_goods_album, array('goodsid' => $id));
			}
			$this->delete_html_file($id, $goods['addtime'], $goods['filename']); */
			if($r > 0){
				$iRtn ++;
			}
		}
		return $iRtn;
	}
	
	/***************************************************************************
	 * 规格属性
	 ***************************************************************************/
	
	public function get_attrs($id){
		$attrs = array();
		$attr_list = $this->db->get_all($this->tb_goods_attr, '*', array('goodsid' => $id));
		if(!empty($attr_list['list'])){
			$prototypes = Prototype::get_prototypes();
			foreach($attr_list['list'] as $row){
				if(is_array($prototypes[$row['prototypeid']]['value'])){
					if(!isset($attrs[$row['prototypeid']]))$attrs[$row['prototypeid']] = array(
						'name'	=> $prototypes[$row['prototypeid']]['name'],
						'type'	=> 'array',
						'value'	=> array(),
					);
					if(isset($prototypes[$row['prototypeid']]['value'][$row['value']])){
						$attrs[$row['prototypeid']]['value'][$row['value']] = $prototypes[$row['prototypeid']]['value'][$row['value']];
					}else{
						$attrs[$row['prototypeid']]['value'] = $row['value'];
					}
				}else{
					$attrs[$row['prototypeid']]= array(
						'name'	=> $prototypes[$row['prototypeid']]['name'],
						'type'	=> 'string',
						'value'	=> $row['value'],
					);
				}
			}
		}
		return $attrs;
	}
	
	public function get_specs($id, $format = false){
		$specs = array();
		$price = array('min' => 0, 'max' => 0);
		$spec_list = $this->db->get_all($this->tb_goods_spec, '*', array('goodsid' => $id));
		if(!$format){
			return $spec_list['list'];
		}
		if(!empty($spec_list['list'])){
			$prototypes = Prototype::get_prototypes();
			foreach($spec_list['list'] as $row){
				if(is_array($prototypes[$row['prototypeid']]['value'])){
					if(!isset($specs[$row['prototypeid']]))$specs[$row['prototypeid']] = array(
						'name'	=> $prototypes[$row['prototypeid']]['name'],
						'type'	=> 'array',
						'value'	=> array(),
					);
					$specs[$row['prototypeid']]['value'][$row['value']] = array(
						'value' => $prototypes[$row['prototypeid']]['value'][$row['value']],
						'price' => $row['price'],
						'quantity' => $row['quantity'],
						'autofill' => $row['autofill'],
					);
				}else{
					$specs[$row['prototypeid']]= array(
						'name'	=> $prototypes[$row['prototypeid']]['name'],
						'type'	=> 'string',
						'value' => $row['value'],
						'price' => $row['price'],
						'quantity' => $row['quantity'],
						'autofill' => $row['autofill'],
					);
				}
				if($row['price'] > 0){
					if($price['min'] == 0 || $row['price'] < $price['min']){
						$price['min'] = $row['price'];
					}
					if($row['price'] > $price['max']){
						$price['max'] = $row['price'];
					}
				}
			}
		}
		return array('price' => $price, 'specs' => $specs);
	}
	
	public function get_attr($goodsid, $prototypeid, $value, $fields = '*'){
		return $this->db->get_row($this->tb_goods_attr, array('goodsid' => $goodsid, 'prototypeid' => $prototypeid, 'value' => $value), $fields);
	}
	
	public function get_spec($goodsid, $prototypeid, $value, $fields = '*'){
		return $this->db->get_row($this->tb_goods_spec, array('goodsid' => $goodsid, 'prototypeid' => $prototypeid, 'value' => $value), $fields);
	}
	
	/*******************************************************************************
	 * 库存
	 *******************************************************************************/
	
	public function reduce_store($goodsid, $prototypeid, $value, $number){
		$stockinfo = $this->get_spec($goodsid, $prototypeid, $value, $fields = '*');
		if(empty($stockinfo['autofill'])){
			$data = array(
				'quantity' 	=> $stockinfo['quantity'] - $number,
				'updatetime'=> TIME,
			);
			return $this->db->update($this->tb_goods_spec, array('goodsid' => $goodsid, 'prototypeid' => $prototypeid, 'value' => $value), $data);
		}
	}
	
	/***************************************************************************
	 * 查询
	 ***************************************************************************/

	public function get_row($id, $fields = '*', $full = false, $cache = false){
		if($cache && !empty($this->goodslist[$id]) && $this->goodslist[$id]['isfull']){
			return $this->goodslist[$id];
		}
		if($full || $cache){
			$sql= <<<SQL
SELECT {$fields} FROM {$this->tb_goods} g
	LEFT JOIN {$this->tb_goods_trends} t
		ON `t`.`goodsid`=`g`.`id`
	WHERE `g`.`id`={$id}
	LIMIT 1
SQL
;
			$this->goodslist[$id] = $this->db->sql_row($sql);
		}else{
			$this->goodslist[$id] = $this->db->get_row($this->tb_goods, array('id' => $id), $fields);
		}
		$this->goodslist[$id]['isfull'] = $full || $cache;
		if(isset($this->goodslist[$id]['describe'])){$this->goodslist[$id]['describe'] = str_replace('{UP_DIR}', UP_DIR, $this->goodslist[$id]['describe']);}
		return $this->goodslist[$id];

	}
	
	public function get_by_filename($filename, $fields = '*', $full = false, $cache = false){
		if($cache && !empty($this->goodslist[$filename]) && $this->goodslist[$filename]['isfull']){
			return $this->goodslist[$filename];
		}
		if($full || $cache){
			$sql= <<<SQL
SELECT {$fields} FROM {$this->tb_goods} g
	LEFT JOIN {$this->tb_goods_trends} t
		ON `t`.`goodsid`=`g`.`id`
	WHERE `g`.`filename`={$filename}
	LIMIT 1
SQL
;
			$this->goodslist[$filename] = $this->db->sql_row($sql);
		}else{
			$this->goodslist[$filename] = $this->db->get_row($this->tb_goods, array('filename' => $filename), $fields);
		}
		$this->goodslist[$filename]['isfull'] = $full || $cache;
		if(isset($this->goodslist[$filename]['describe'])){$this->goodslist[$filename]['describe'] = str_replace('{UP_DIR}', UP_DIR, $this->goodslist[$filename]['describe']);}
		return $this->goodslist[$filename];
	}
	
	// 取列表	
	public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET){
		// 如果“外表小而内表大”，貌似EXISTS比IN高效
		$where = array();
		if(empty($select['childs'])){
			if(!empty($select['catid'])){			$where[] = "`g`.`catid`='{$select['catid']}'";				}	
		}else{
			$where[] = "`g`.`catid` IN ({$select['childs']})";
		}
		if(!empty($select['keyword'])){				$where[] = "`g`.`name` LIKE '%{$select['keyword']}%'";		}
		if(!empty($select['range'])){
			$range_arr = explode('-', $select['range']);
			if(empty($select['price_min']))$select['price_min'] = $range_arr[0];
			if(empty($select['price_max']) || $range_arr[1] != '~')$select['price_max'] = $range_arr[1];
		}
		$select['price_min'] = empty($select['price_min']) ? 0 : intval($select['price_min']);
		if($select['price_min'] < 0)$select['price_min'] = 0;
		$select['price_max'] = empty($select['price_max']) ? 0 : intval($select['price_max']);
		if($select['price_min'] > $select['price_max'])$select['price_max'] = 0;
		if(!empty($select['price_min'])){			$where[] = "`g`.`price`>={$select['price_min']}";			}
		if(!empty($select['price_max'])){			$where[] = "`g`.`price`<={$select['price_max']}";			}
		
		if(!empty($select['recommend'])){
			if($select['recommend'] == 'normal')$select['recommend'] = '';
			$where[] = "`g`.`recommend`='{$select['recommend']}'";		
		}
		if(!empty($select['labeltype'])){
			$where[] = "`g`.`labeltype`='{$select['labeltype']}'";
		}
		if(!empty($select['brand'])){
			if(is_array($select['brand'])){
				$where[] = "`g`.`brand` IN (".implode(',', $select['brand']).")";
			}else{
				$where[] = "`g`.`brand`='{$select['brand']}'";
			}
		}
		if(!empty($select['salesinfo'])){			$where[] = "`g`.`salesinfo`='{$select['salesinfo']}'";		}
		if(!empty($select['prototype'])){
			$where_spec = array();
			foreach($select['prototype'] as $prototypeid => $value){
				$wh = array("`s`.`prototypeid`={$prototypeid}");
				if(is_array($value)){
					$wh[] = "`s`.`value` IN ('".implode("','", $value)."')";
				}else{
					$wh[] = "`s`.`value`='{$value}'";
				}
				$where_spec[] = "(".implode(' AND ', $wh).")";
			}
			$where[] = " EXISTS (SELECT `goodsid` FROM `{$this->tb_goods_spec}` AS `s` WHERE `s`.`goodsid`=`g`.`id` AND ".implode(' OR ', $where_spec).")";
		}
		$where[] = "`g`.`isdel`=0";	// 只显示未删除
		if(empty($where)){
			$where = '';
		}else{
			$where = " WHERE ".trim(implode(' AND ', $where));
		}
		if(!empty($select['kept']))$where .= $select['kept'];

		// 排序
		$orderby = array();
		if(!empty($order)){
			$allfields = $this->db->get_fields($this->tb_goods);
			foreach ($order as $field => $direction){
				if(is_array($direction) || is_numeric($direction)){continue;}
				$direction = strtoupper($direction);
				if($direction != 'ASC' && $direction != 'DESC'){continue;}
				switch ($field) {
					case 'orderby_price':
						$orderby[] = "`g`.`price` {$direction}";
						break;
					case 'orderby_sales':
						$orderby[] = "`t`.`sales` {$direction}";
						break;
					case 'orderby_comments':
						$orderby[] = "`t`.`comments` {$direction}";
						break;
					case 'orderby_score':
						$orderby[] = "`t`.`score` {$direction}";
						break;
					case 'orderby_views':
						$orderby[] = "`t`.`views` {$direction}";
						break;
					case 'orderby_favorites':
						$orderby[] = "`t`.`favorites` {$direction}";
						break;
					case 'orderby_id':
						$orderby[] = "`g`.`id` {$direction}";
						break;
					
					default:
						if(array_key_exists($field, $allfields)){
							$orderby[] = "`g`.`{$field}` {$direction}";
						}
						break;
				}
			}
		}
		if(empty($orderby)){
			$orderby[] = "`g`.`id` DESC";
		}
		$orderby = implode(',', $orderby);

		$sql = <<<SQL
SELECT {$fields} FROM `{$this->tb_goods}` AS `g`
	LEFT JOIN `{$this->tb_goods_trends}` AS `t`
	ON `t`.`goodsid`=`g`.`id`
	{$where}
	ORDER BY {$orderby} 
SQL
;
		return $this->db->sql_list($sql, $page, $size, $offset);
	}
	
	/************************************************************************
	 * 相册
	 ************************************************************************/
	
	public function get_album_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10){
		return $this->db->get_list($this->tb_goods_album, $fields, $select, $order, $page, $size, $offset);
	}
	
	public function get_album_all($goodsid, $fields = '*'){
		return $this->db->get_all($this->tb_goods_album, $fields, array('goodsid' => $goodsid), array('iscover' => 'DESC', 'rank' => 'DESC', 'id' => 'ASC'));
	}
	
	public function get_album_row($id, $fields = '*'){
		return $this->db->get_row($this->tb_goods_album, array('id' => $id), $fields);
	}
	
	public function get_album_first($goodsid, $fields = '*'){
		return $this->db->sql_row("SELECT $fields FROM `{$this->tb_goods_album}` WHERE `goodsid`=$goodsid ORDER BY `iscover` DESC,`rank` DESC,`id` ASC LIMIT 1");
	}

	/*******************************************************************************
	 * 取动态信息
	 *******************************************************************************/

	public function get_trends($goodsid, $fields = '*'){
		return $this->db->get_row($this->tb_goods_trends, array('goodsid' => $goodsid), $fields);
	}

	/********************************************************************************
	 * 更新静态文件
	 ********************************************************************************/
	
	public function mkhtml($post){
		if(empty($post['list'])){
			return true;
		}
		return $this->update_html_files($post['list']);
	}

	public function update_html_files($list){
		if(in_array('goods_content', $list)){
			$goods_content = true;
		}else{
			$goods_content = false;
		}
		foreach ($list as $key){
			if($key == 'index'){
				File::delFile(WEB_PTH.'index.html');
			}elseif($key == 'goods_index'){
				$this->delete_html_list(0, $goods_content);
			}else{
				$this->delete_html_list($key, $goods_content);
			}
		}
		return true;
	}
	
	private function delete_html_file($id, $addtime, $filename = ''){
		if(!empty($filename)){
			File::delFile(PUB_PTH.'goods/'.$filename.'.html');
		}
		File::delFile(PUB_PTH.'goods/'.time_to_path($addtime).'/'.$id.'.html');
	}
	
	private function delete_html_list($key, $goods_content = false){
		$catid = intval(str_replace('goods_category_', '', $key));
		if($catid > 0){
			if($goods_content == true){
				$list = $this->get_list('id,filename,addtime', array('catid' => $catid), array(), 1, 2000);
				if(isset($list['list']) && is_array($list['list'])){
					foreach($list['list'] as $row){
						$this->delete_html_file($row['id'], $row['addtime'], $row['filename']);
					}
				}
			}
			
			//$__f_goods_cats = cache_read('goods_categorys.php');
			//$mark = $__f_goods_cats['category_list'][$catid]['mark'].'/';
			$mark = Goodscat::get_category($catid, 'mark');
			$mark .= '/';
		}else{
			$mark = '';
		}
		$files = File::getFiles(PUB_PTH.'goods/'.$mark, false);
		foreach ($files as $file){
			File::delFile(PUB_PTH.'goods/'.$mark.$file);
		}
	}
}
?>